﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Red.Controls.Shell;
using Red.Controls.ViewModels;
using P4 = Red.Core.Perforce;

namespace Red.Controls.SourceControl
{
    public partial class SelectPendingChangelist : RedDialog
    {
        #region Data

        private P4.Mediator _sourceControl;

        #endregion Data

        #region Properties

        public bool IsSuccess { get { return DialogResult.HasValue && DialogResult.Value; } }

        public P4.Mediator SourceControl { get { return _sourceControl; } set { _sourceControl = value; Populate(); } }

        public SelectPendingChangelistViewModel ViewModel { get; private set; } = new SelectPendingChangelistViewModel();

        #endregion Properties

        #region C-tor

        public SelectPendingChangelist()
        {
            InitializeComponent();

            FrameworkElement element = (FrameworkElement)Content;
            element.DataContext = ViewModel;
            DataContext = ViewModel;

            Type = RedDialogType.OkCancel;
            ResizeMode = ResizeMode.CanResizeWithGrip;
            SizeToContent = SizeToContent.Manual;
            ShowMinButton = false;
        }

        #endregion C-tor

        #region Private Methods

        private void Populate()
        {
            // Add default "New" changelist
            NewPendingChangelistInfo newPendingChangelist = new NewPendingChangelistInfo();
            ViewModel.Changelists.Add( newPendingChangelist );

            // Extract and add all existing pending changelists from perforce
            IEnumerable< PendingChangelistInfo > pendingChangelists = from cl in SourceControl.GetChangelists() select new PendingChangelistInfo { Description = cl.Description, Id = cl.Id };
            ViewModel.Changelists.AddRange( pendingChangelists );

            // Select the most recent changelist by default
            ViewModel.SelectedChangelist = pendingChangelists.DefaultIfEmpty( newPendingChangelist ).First();
        }

        #endregion Private Methods
    }
}
